<template>
	<view class="content">
		<!-- 公告栏 -->
		<view class="announcement">
			<view class="announcement-content">
				报餐时间为：午餐在当天8:40前，晚餐当天为11:00前，下午6点后放开次日报餐。修改报餐请再次提交。报餐有问题请联系管理员谢宝来：15170470622。
			</view>
		</view>

		<view class="meal-form">
			<view class="form-item">
				<text>姓名：</text>
				<input v-model="name" placeholder="请输入姓名" />
			</view>
			<view class="form-item">
				<text>部门：</text>
				<picker mode="selector" :range="departments" @change="onDepartmentChange">
					<view class="picker">
						{{ department || '请选择部门' }}
					</view>
				</picker>
			</view>
			<view class="form-item">
				<text>中餐：</text>
				<switch :checked="meal.lunch" @change="onLunchChange" :class="{ 'disabled-switch': isLunchDisabled }" />
			</view>
			<view class="form-item">
				<text>晚餐：</text>
				<switch :checked="meal.dinner" @change="onDinnerChange"
					:class="{ 'disabled-switch': isDinnerDisabled }" />
			</view>
			<button @click="submitMeal">提交</button>
		</view>
	</view>
</template>

<script>

export default {
	data() {
		return {
			title: '报餐系统',
			name: '',
			department: '',
			departments: [
				'综合办公室',
				'人力资源部',
				'财务部',
				'科技管理部',
				'采矿中心',
				'选矿中心',
				'冶金中心',
				'材料中心',
				'智能装备中心',
				'智能矿冶中心',
				'华安公司',
				'检测公司',
				'地勘公司',
				'物业公司'
			],
			meal: {
				lunch: false,
				dinner: false
			},
			isLunchDisabled: false,
			isDinnerDisabled: false,
			lunch_hour: 8,
			lunch_minute: 40,
			dinner: 11,
			next: 18,
		}
	},
	methods: {
		convertUTCToBeijingDate(utcDate) {
			// 创建一个新的 Date 对象，解析传入的 UTC 时间
			let date = new Date(utcDate);
			// 获取北京的时区偏移（东8区）
			date.setTime(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
			date.setHours(date.getHours() + 8);
			// 格式化日期为本地时间
			return new Date(date);
		},

		// 页面加载时检查时间
		checkMealTime() {
			const beijingTime = this.convertUTCToBeijingDate(new Date());
			const hours = beijingTime.getHours();

			// 判断是否在前一天下午4点后
			if (hours >= this.next) {
				// 如果是前一天下午4点后，放开按钮
				this.isLunchDisabled = false;
				this.isDinnerDisabled = false;
			} else {
				// 否则，按正常时间限制
				// 判断午餐是否超时
				if (hours > this.lunch_hour || (hours === this.lunch_hour && beijingTime.getMinutes() > this.lunch_minute)) {
					this.isLunchDisabled = true;
				}

				// 判断晚餐是否超时
				if (hours >= this.dinner) {
					this.isDinnerDisabled = true;
				}
			}
		},

		// 部门选择
		onDepartmentChange(e) {
			this.department = this.departments[e.detail.value];
		},

		// 中餐选择
		onLunchChange(e) {
			if (this.isLunchDisabled) {
				return; // 直接返回，不弹出提醒
			}
			this.meal.lunch = e.detail.value;
		},

		// 晚餐选择
		onDinnerChange(e) {
			if (this.isDinnerDisabled) {
				return; // 直接返回，不弹出提醒
			}
			this.meal.dinner = e.detail.value;
		},

		// 提交报餐
		async submitMeal() {
			if (!this.name || !this.department) {
				uni.showToast({
					title: '请填写姓名和部门',
					icon: 'none'
				});
				return;
			}

			// 保存用户输入的姓名和部门
			uni.setStorageSync('lastName', this.name);
			uni.setStorageSync('lastDepartment', this.department);

			// 获取当前时间并调整为北京时间
			const beijingTime = this.convertUTCToBeijingDate(new Date());
			const hours = beijingTime.getHours();

			// 判断是否在前一天下午4点后
			const isNextDayMeal = hours >= this.next;

			// 如果午餐和晚餐都没有选择，提醒取消报餐
			if (!this.meal.lunch && !this.meal.dinner) {
				const action = isNextDayMeal ? 'cancelNextDayMeal' : 'cancelTodayMeal';
				const res = await uniCloud.callFunction({
					name: 'canteen',
					data: {
						action: action,
						data: {
							name: this.name,
							department: this.department
						}
					}
				});

				if (res.result.code === 0) {
					uni.showToast({
						title: isNextDayMeal ? '次日取消成功' : '当日取消成功',
						icon: 'success'
					});
					// 清空表单
					this.meal = {
						lunch: false,
						dinner: false
					};
				} else {
					uni.showToast({
						title: '取消报餐失败',
						icon: 'none'
					});
				}
				return;
			}

			// 根据是否次日报餐调用不同的云函数
			const action = isNextDayMeal ? 'submitNextDayMeal' : 'submitTodayMeal';
			const res = await uniCloud.callFunction({
				name: 'canteen',
				data: {
					action: action,
					data: {
						name: this.name,
						department: this.department,
						...this.meal
					}
				}
			});

			// 打印提交后的 res
			console.log('res:', res);

			if (res.result.code === 0) {
				uni.showToast({
					title: isNextDayMeal ? (res.result.isUpdate ? '次日修改成功' : '次日报餐成功') : (res.result.isUpdate ? '当日修改成功' : '当日报餐成功'),
					icon: 'success'
				});
				// 只清空中餐和晚餐的选择
				this.meal = {
					lunch: false,
					dinner: false
				};
			} else {
				uni.showToast({
					title: '报餐失败',
					icon: 'none'
				});
			}
		}
	},
	mounted() {
		// 页面加载时检查时间
		this.checkMealTime();

		// 读取上次输入的姓名和部门
		const lastName = uni.getStorageSync('lastName');
		const lastDepartment = uni.getStorageSync('lastDepartment');

		if (lastName) {
			this.name = lastName;
		}
		if (lastDepartment) {
			this.department = lastDepartment;
		}
	}
}
</script>

<style>
.content {
	padding: 20px;
	max-width: 600px;
	margin: 0 auto;
}

.meal-form {
	margin-top: 30px;
	padding: 20px;
	background-color: #fff;
	border-radius: 16px;
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.form-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 20px;
	padding: 15px;
	background-color: #f8f9fa;
	border-radius: 12px;
}

.form-item text {
	font-size: 16px;
	color: #333;
	min-width: 60px;
}

.form-item input {
	flex: 1;
	margin-left: 10px;
	padding: 10px 12px;
	border: 1px solid #e0e0e0;
	border-radius: 8px;
	font-size: 14px;
	color: #333;
	background-color: #fff;
	transition: border-color 0.3s ease, box-shadow 0.3s ease;
}

.form-item input:focus {
	border-color: #007aff;
	box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.1);
	outline: none;
}

.form-item input::placeholder {
	color: #999;
}

switch {
	transform: scale(0.9);
}

button {
	margin-top: 20px;
	background-color: #007aff;
	color: #fff;
	border-radius: 12px;
	font-size: 16px;
	padding: 12px 0;
	transition: all 0.3s ease;
	border: none;
	width: 100%;
}

button::after {
	border: none;
}

button:active {
	transform: scale(0.98);
	opacity: 0.9;
}

.picker {
	flex: 1;
	margin-left: 10px;
	padding: 10px 12px;
	border: 1px solid #e0e0e0;
	border-radius: 8px;
	font-size: 14px;
	color: #333;
	background-color: #fff;
	transition: border-color 0.3s ease, box-shadow 0.3s ease;
}

.picker:active {
	border-color: #007aff;
	box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.1);
}

/* 禁用状态样式 */
.disabled-switch {
	opacity: 0.5;
	pointer-events: none;
}

/* 公告栏样式 */
.announcement {
	width: 100%;
	overflow: hidden;
	white-space: nowrap;
	background-color: #fffbe6;
	padding: 10px;
	border-radius: 8px;
	margin-bottom: 20px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.announcement-content {
	display: inline-block;
	padding-left: 100%;
	animation: scroll 20s linear infinite;
	font-size: 14px;
	color: #d48806;
}

@keyframes scroll {
	0% {
		transform: translateX(100%);
	}

	100% {
		transform: translateX(-100%);
	}
}
</style>
